﻿using System.Collections.Generic;
using System.Linq;
using UnityEngine;

public static class AllCheckpoints
{
    public static List<GameObject> Checkpoints;
    public static List<Checkpoint> PassedCheckpoints;

    public static void InitializeCheckpoints()
    {
        Checkpoints = new List<GameObject>();
        PassedCheckpoints = new List<Checkpoint>();
        GetCheckpointsForCurrentLevel();
    }

    public static bool AddCheckpointToPassedCheckpoints(double time, int score, string name)
    {
        bool addNewEntry = PassedCheckpoints.All(checkpoint => checkpoint.Name != name);

        if (addNewEntry)
            PassedCheckpoints.Add(new Checkpoint(time, PassedCheckpoints.Count, Checkpoints[PassedCheckpoints.Count],
                                                 score, name));

        return addNewEntry;
    }

    private static void GetCheckpointsForCurrentLevel()
    {
        GameObject[] temp = GameObject.FindGameObjectsWithTag("Checkpoint");

        foreach (GameObject gameObject in temp)
            Checkpoints.Add(gameObject);

        Checkpoints = Checkpoints.OrderBy(cp => cp.transform.position.x).ToList();
        for (int i = 0; i < Checkpoints.Count; i++)
        {
            Checkpoints[i].name = "Checkpoint" + i;
        }
    }

    public static Checkpoint GetLastCheckpoint()
    {
        return PassedCheckpoints.Last();
    }
}

public class Checkpoint
{
    public Checkpoint(double time, int id, GameObject gObject, int score, string name)
    {
        Name = name;
        Time = time;
        Id = id;
        PlayerEnergy = Player.Energy;
        PlayerHp = Player.HitPoints;
        Score = score;
        Coordinates = Player.Object.transform.position;
        Powerup = Player.Powerup;
    }

    public string Name { get; private set; }
    public int Id { get; private set; }
    public int PlayerEnergy { get; private set; }
    public int PlayerHp { get; private set; }
    public int Score { get; private set; }
    public double Time { get; private set; }
    public Vector3 Coordinates { get; private set; }
    public Powerup Powerup { get; private set; }
}